package com.example.demo.services;


import com.example.demo.config.ChatServiceException;
import com.example.demo.config.JackConfig;
import com.example.demo.identity.ChatFriend;
import com.example.demo.identity.ChatMessages;
import com.example.demo.identity.User;
import com.example.demo.mapper.ChatMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class RedisService {

    private final static Logger logger = LoggerFactory.getLogger(RedisService.class);

    private final RedisTemplate<String, Object> redisTemplate;

    private static ChatMapper chatMapper;

    /*
        注意：这里的名称要与JackConfig中的Bean的名称一致，不然会出错
        Qualifier注解的作用：用于在依赖注入时指定注入的Bean的名称
    */
    @Qualifier("jacksonObjectMapper")
    @Autowired
    private ObjectMapper objectMapper;

    public RedisService(RedisTemplate<String, Object> redisTemplate, ChatMapper chatMapper) {
        this.redisTemplate = redisTemplate;
        RedisService.chatMapper = chatMapper;
    }

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private JackConfig jackConfig;

    /**
     * //     * @param chatId     聊天会话的唯一标识，用于区分不同的聊天。
     *
     * @param senderId   发送消息的用户ID。
     * @param receiverId 接收消息的用户ID。
     * @param message    聊天消息的内容。
     *                   //     * @param messageId  我也忘了这是什么了哈哈（优化前用户redis存储的，后期改为了MongoDB存储，暂时不用，后期维护再添加）
     */
    public void saveChatMessage(String senderId, String receiverId, String message, String nickName, String avatar) throws JsonProcessingException {
        // 创建消息内容
//        Map<String, Object> chatMessage = createChatMessages(senderId, receiverId, message);
//        拼接出一个用于存储消息内容的Redis键
//        String messageKey = "chat:message:" + messageId;
        // 将消息内容存储到redis的hash结构中
//        redisTemplate.opsForHash().putAll(messageKey, chatMessage);

//        为消息内容设置过期时间
//        redisTemplate.expire(messageKey, expireTimeInSeconds, TimeUnit.SECONDS);

        // 将消息Id和时间戳存储到sorted set中，将时间戳作为score
//        redisTemplate.opsForZSet().add("chat:messages:" + chatId, messageId, System.currentTimeMillis());

        // 将chatId添加到发送方和接收方的聊天列表中
//        redisTemplate.opsForSet().add("chat:conversations:" + senderId, chatId);
//        redisTemplate.opsForSet().add("chat:conversations:" + receiverId, chatId);

//        数据持久化到mongodb中
        saveToMongoDB(senderId, receiverId, message, nickName, avatar);
    }

    // 将数据持久化到 MongoDB 中
    private void saveToMongoDB(String senderId, String receiverId, String message, String nickName, String avatar) throws JsonProcessingException {
        // 提取公共字段
        String timeStamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String, Object> baseMessage = new HashMap<>();
        baseMessage.put("senderId", senderId);
        baseMessage.put("receiverId", receiverId);
        baseMessage.put("timeStamp", timeStamp);
        baseMessage.put("userNickName", nickName);
        baseMessage.put("userNickAvatar", avatar);

        // 尝试解析message为JSON
        ObjectMapper objectMapper = new ObjectMapper();
        String type = "TEXT"; // 默认type类型是文本类型
        JsonNode jsonNode = null;

        try {
            jsonNode = objectMapper.readTree(message);
            if (jsonNode.has("fileName")) {
                type = "FILE";
            }
        } catch (JsonProcessingException e) {
            // 如果解析失败，说明message不是JSON格式，直接将其作为普通文本处理
            System.out.println("Message is not a valid JSON: " + message);
        }

        baseMessage.put("message", message);
        baseMessage.put("type", type);

        // 构建 from-to 消息
        Map<String, Object> fromToMessage = new HashMap<>(baseMessage);
        fromToMessage.put("messageKey", UUID.randomUUID().toString().substring(0, 14));
        fromToMessage.put("chatId", senderId + "-" + receiverId);
        mongoTemplate.save(fromToMessage, "chatMessages");
    }

    //    获取用户对话信息          这个不用了，淘汰的版本
    public List<Map<Object, Object>> getUserMessages(String senderId, String receiverId) {
        // 1、获取发送者消息列表ID
        Set<Object> chatIdsA = getUserConversations(senderId);
        // 2、获取接受者消息列表Id
        Set<Object> chatIdsB = getUserConversations(receiverId);

        // 3、合并两个集合并去重
        Set<Object> allChatIds = new HashSet<>(chatIdsA);
        allChatIds.addAll(chatIdsB);

        if (allChatIds.isEmpty()) {
            throw new RuntimeException("A和B之间没有聊天会话");
        }

        // 创建一个ArrayList来存储所有消息内容
        List<Map<Object, Object>> messageList = new ArrayList<>();

        // 遍历所有会话Id，获取每个会话的消息内容
        for (Object chatId : allChatIds) {
            Set<Object> messageIds = redisTemplate.opsForZSet().reverseRange("chat:messages:" + chatId, 0, -1);
            assert messageIds != null;
            for (Object messageId : messageIds) {
//                会话ID验证
                if (!isValidChatId(chatId.toString(), senderId, receiverId)) {
//                    如果会话Id不合法则跳过当前会话
                    continue;
                }
                // 构建消息内容的键
                String messageKey = "chat:message:" + messageId;
                // 在redis的hash结构中获取消息内容
                Map<Object, Object> messageContent = redisTemplate.opsForHash().entries(messageKey);
                // 将聊天内容添加到列表中
                messageList.add(messageContent);
            }
        }

//        根据timeStamp进行排序
        Collections.sort(messageList, new Comparator<Map<Object, Object>>() {
            @Override
            public int compare(Map<Object, Object> o1, Map<Object, Object> o2) {
                String timeStamp1 = (String) o1.get("timeStamp");
                String timeStamp2 = (String) o2.get("timeStamp");
                return timeStamp1.compareTo(timeStamp2);
            }
        });


        return messageList;
    }

    //    添加好友信息（将添加好友的信息存储到redis中）
    public void addFriendRequest(String fromUserId, String toUserId, String messageContent, String username, String friendAvatar, String requestId) {
//        生成好友请求消息的唯一Id（为了方便后续的同意、拒绝好友请求则不使用UUID生成的随机字符串了）
//        String requestId = UUID.randomUUID().toString().substring(0, 8);
//        生成好友请求的唯一key
        String friendRequestShipKey = "friendRequest:" + fromUserId + ":" + toUserId;
        // 检查是否已经发送过好友请求
        if (redisTemplate.hasKey(friendRequestShipKey)) {
            throw new ChatServiceException("已经发送过好友请求");
        }

        // 存储好友请求信息
        Map<String, Object> friendRequest = createFriendRequest(fromUserId, toUserId, messageContent, username, friendAvatar, requestId);

        // 将好友请求信息存储到 Redis 中
//        String zSetKey = "friendRequest:inbox:" + toUserId;
        try {
            redisTemplate.opsForHash().putAll(friendRequestShipKey, friendRequest);
//            将好友请求的唯一key添加到收件箱的有序集合中
            String zSetKey = "friendRequest:inbox:" + toUserId;
            redisTemplate.opsForZSet().add(zSetKey, friendRequestShipKey, System.currentTimeMillis());
        } catch (Exception e) {
            logger.error("Failed to add friend request: fromUserId={}, toUserId={}", fromUserId, toUserId, e);
            throw new ChatServiceException("Failed to add friend request", e);
        }
    }

    //    同意好友请求        升级之后的函数多了一个返回值
    public boolean acceptFriendRequest(Map<String, String> fromUserFriend, Map<String, String> toUserFriend) {
        try {
            String fromUserId = fromUserFriend.get("friendId");
            String toUserId = toUserFriend.get("friendId");
            // 构建好友请求的键
            String friendRequestKey = "friendRequest:" + fromUserId + ":" + toUserId;
            if (!redisTemplate.hasKey(friendRequestKey)) {
                throw new RuntimeException("好友请求信息不存在或已经被处理");
            }
//        删除好友请求记录
            redisTemplate.delete(friendRequestKey);

//        添加好友关系
            String userFriendKeyFrom = "friends:" + fromUserId;
            String userFriendKeyTo = "friends:" + toUserId;
            redisTemplate.opsForSet().add(userFriendKeyFrom, toUserId);
            redisTemplate.opsForSet().add(userFriendKeyTo, fromUserId);

//        添加备注信息到Hash
            String userRemarkKeyFrom = "remarks:" + fromUserId;
            String userRemarkKeyTo = "remarks:" + toUserId;
//        获取Hash操作接口
            HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();
//        设置备注信息，默认为空字符串
            hashOps.putIfAbsent(userRemarkKeyFrom, toUserId, "");
            hashOps.putIfAbsent(userRemarkKeyTo, fromUserId, "");

//        添加分组信息到Hash
            String userGroupKeyFrom = "friendGroups:" + fromUserId;
            String userGroupKeyTo = "friendGroups:" + toUserId;
//        设置分组信息，默认为空字符串（修改之后：默认都是在普通friend分组中）
            hashOps.putIfAbsent(userGroupKeyFrom, toUserId, "friends-list");
            hashOps.putIfAbsent(userGroupKeyTo, fromUserId, "friends-list");

//        添加好友详细信息到hash（这是后期添加的(2025.8.1)）
            String userDetailKeyFrom = "friendDetails:" + fromUserId;
            String userDetailKeyTo = "friendDetails:" + toUserId;
//        构建好友详细信息的json字符串
            String fromUserDetailJson = objectMapper.writeValueAsString(fromUserFriend);
            String toUserDetailJson = objectMapper.writeValueAsString(toUserFriend);
            hashOps.putIfAbsent(userDetailKeyFrom, toUserId, toUserDetailJson);
            hashOps.putIfAbsent(userDetailKeyTo, fromUserId, fromUserDetailJson);

            return true;
        } catch (JsonProcessingException e) {
            logger.info(e.getMessage());
            return false;
        }
    }


    /**
     * 获取聊天消息的 ID 列表
     *
     * @param chatId 聊天会话 ID
     * @param start  开始索引
     * @param count  获取的消息数量
     * @return 消息 ID 列表
     */
    //    组合redis中的sorted set数据和hash数据（优化之后的函数：批量查询，可以将多个Id一次性查询，减少Redis的交互次数）
    public List<Map<Object, Object>> getAllMessages(String chatId, int start, int count) {
        ArrayList<Object> messageIds = getIdsFromZSet("chat:messages:" + chatId, start, count);
        return getDetailsFromHashList(messageIds, "chat:message:");
    }


    //    获取所有好友请求信息的详细信息
    public List<Map<Object, Object>> getAllFriendRequests(String toUserId, int start, int count) {
        // 构建好友请求的 Sorted Set 键
        String zSetKey = "friendRequest:inbox:" + toUserId;

        // 获取好友请求的 ID 列表
        ArrayList<Object> requestIds = getIdsFromZSet(zSetKey, start, count);

        // 提取不带前缀的唯一标识
        List<Object> uniqueIds = requestIds.stream().map(id -> ((String) id).substring("friendRequest:".length())).collect(Collectors.toList());
//        根据请求Id列表批量获取好友请求的详细信息
        return getDetailsFromHashList(uniqueIds, "friendRequest:");
    }


    //    提取公共方法
    private ArrayList<Object> getIdsFromZSet(String zSetKey, int start, int count) {
        Long size = redisTemplate.opsForZSet().size(zSetKey);
        if (size == 0) {
            throw new ChatServiceException("No items found for key: " + zSetKey);
        }
        if (start >= size) {
            throw new ChatServiceException("Start index out of range for key: " + zSetKey);
        }
        int end = (int) Math.min(start + count - 1, size - 1);
        Set<Object> ids = redisTemplate.opsForZSet().reverseRange(zSetKey, start, end);
        if (ids == null) {
            throw new ChatServiceException("No items found for key: " + zSetKey);
        }
        return new ArrayList<>(ids);
    }

    /**
     * @param senderId   发送者ID。
     * @param receiverId 接收者ID。
     * @param message    消息内容。
     * @return
     */
    //    创建聊天消息
    private List<Map<String, Object>> createChatMessages(String senderId, String receiverId, String message) {
        List<Map<String, Object>> chatMessages = new ArrayList<>();

        // 创建基础消息对象，包含公共字段
        Map<String, Object> baseMessage = new HashMap<>();
        baseMessage.put("senderId", senderId);
        baseMessage.put("receiverId", receiverId);
        baseMessage.put("message", message);
        baseMessage.put("timeStamp", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        // 创建 from-to 消息
        Map<String, Object> fromToMessage = new HashMap<>(baseMessage); // 克隆基础消息对象
        fromToMessage.put("chatId", senderId + "-" + receiverId);
        fromToMessage.put("randomKey", UUID.randomUUID().toString().substring(0, 5));
        chatMessages.add(fromToMessage);

        // 创建 to-from 消息
        Map<String, Object> toFromMessage = new HashMap<>(baseMessage); // 克隆基础消息对象
        toFromMessage.put("chatId", senderId + "-" + receiverId);
        toFromMessage.put("senderId", receiverId); // 交换 senderId 和 receiverId
        toFromMessage.put("receiverId", senderId);
        toFromMessage.put("randomKey", UUID.randomUUID().toString().substring(0, 5));
        chatMessages.add(toFromMessage);

        return chatMessages;
    }

    //    批量获取Redis Hash中的详细信息，减少代码冗余
    private List<Map<Object, Object>> getDetailsFromHashList(List<Object> ids, String keyPrefix) {
        if (ids == null || ids.isEmpty()) {
            throw new ChatServiceException("No valid IDs found");
        }
        List<Map<Object, Object>> detailsList = new ArrayList<>();
        for (Object id : ids) {
            if (id instanceof String) {
                String key = keyPrefix + id;
                Map<Object, Object> details = redisTemplate.opsForHash().entries(key);
                if (!details.isEmpty()) {
                    detailsList.add(details);
                }
            } else {
                logger.error("Invalid ID type: {}", id.getClass());
            }
        }
        return detailsList;
    }


    /**
     * @param userId 用户id
     * @return 返回userId的好友列表
     */
    //    获取用户好友列表信息
    public List<Map<String, Object>> getUserFriendList(String userId) {
        String key = "friends:" + userId;
        Set<Object> friendSet = redisTemplate.opsForSet().members(key);
        assert friendSet != null;
        ArrayList<Object> friendList = new ArrayList<>(friendSet);

//        定义一个List来存储用户好友信息列表，包含备注信息、分组信息（这是后期添加的）
        List<Map<String, Object>> result = new ArrayList<>();

//        1、获取Hash操作接口
        HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();

        for (Object friend : friendList) {
//            每个friend是一个字符串，表示好友的唯一标识
            String friendId = (String) friend;
//            在redis或其他存储模式中获取相应的详细信息
            ChatFriend chatFriends = chatMapper.getUserFriendList(friendId);

//            检查chatFriends是否为null
            if (chatFriends != null) {
//                使用uu_id作为键
//                String uuId = chatFriends.getUu_id();     // 避免更复杂的对象嵌套，所以不需要这个变量了
//                2、获取好友备注信息    在这里获得的remark要用Object来接收，因为redis中存储的可能是String、Integer（当然这个没用了哈哈）
                String remardKey = "remarks:" + userId;     // 当前用户的好友备注键
                String remark = hashOps.get(remardKey, friendId);   // 获取好友的备注
                if (remark == null) remark = "";        //  如果没有备注信息，则默认为空字符串

//                3、获取好友分组信息
                String groupKey = "friendGroups:" + userId;
                String group = hashOps.get(groupKey, friendId);
                if (group == null) group = "";      // 如果没有分组信息，则默认为空字符串

//                3、将将好友的详细信息和备注信息存储到HashMap中，uuId是键
                Map<String, Object> friendInfo = new HashMap<>();
                friendInfo.put("friendId", friend);
                friendInfo.put("friendDetails", chatFriends);
                friendInfo.put("remark", remark);
                friendInfo.put("group", group);
//                if (uuId != null) {
//                    将好友的详细信息存储到hashmap中，uuId是键
//                    result.put(uuId, chatFriends);
//                }

                result.add(friendInfo);
            }
        }
        return result;
    }

    /**
     * @param userId          用户Id
     * @param friendRequestId 好友添加好友请求消息Id
     */
    //    删除/拒绝好友请求消息
    public void refuseUserFriendRequest(String userId, String friendRequestId) {
//        构建好友请求的key
        String friendRequestKey = "friendRequest:" + friendRequestId + ":" + userId;
//        举个例子：friendRequest:f99985a3-ea08-4:465180dc-53c2-4        在这里的f99985a3-ea08-4（A）是申请添加好友的uu_id，465180dc-53c2-4（B）是被申请用户，是A向B申请，B可以同意、拒绝A的申请，但是B不能对申请进行任何处理（同意、拒绝、撤回）
//        检查好友请求是否存在
        if (!redisTemplate.hasKey(friendRequestKey)) {
            throw new ChatServiceException("好友请求信息不存在");
        }

//        删除好友请求记录
        try {
            redisTemplate.delete(friendRequestKey);
        } catch (Exception e) {
            logger.error("删除好友请求失败：fromUserId={}, toUserId={}", userId, friendRequestId, e);
            throw new ChatServiceException("删除好友请求失败", e);
        }

    }


    /**
     * @param userId 用户id
     * @return 返回会话列表id
     */
//    获取用户会话列表
    public Set<Object> getUserConversations(String userId) {
        return redisTemplate.opsForSet().members("chat:conversations:" + userId);
    }

    //    会话ID验证
    private boolean isValidChatId(String chatId, String senderId, String receiverId) {
//        检查会话Id是否包含发送者和接收者的Id
        return chatId.contains(senderId) && chatId.contains(receiverId);
    }

    /**
     * @param userId   当前登录用户Id
     * @param friendId 要删除的好友Id
     */
    public void deleteFriend(String userId, String friendId) throws ChatServiceException {
        // 构建好友关系的键
        String userFriendKey = "friends:" + userId;
        String friendFriendKey = "friends:" + friendId;

        // 检查好友关系是否存在
        if (
                (Boolean.FALSE.equals(redisTemplate.opsForSet().isMember(userFriendKey, friendId))) ||
                        Boolean.FALSE.equals(redisTemplate.opsForSet().isMember(friendFriendKey, userId))) {
            throw new ChatServiceException("好友关系不存在！");
        }
        try {
            // 删除好友操作
            // 删除聊天对话信息（先删除hash tables中的消息信息，再删除sorted sets对应的信息） 在这个函数中也进行删除conversations、friendslist等操作
            deleteConversationMessages(userId, friendId);
        } catch (Exception e) {
            logger.error("删除好友失败：userId={}, friendId={}", userId, friendId, e);
            throw new ChatServiceException("删除好友失败", e);
        }
    }

    // 删除用户之间的对话信息
    private void deleteConversationMessages(String userId, String friendId) {
        // 获取两个用户的对话列表（Conversations）
        Set<Object> conversations_user = redisTemplate.opsForSet().members("chat:conversations:" + userId);
        Set<Object> conversations_friend = redisTemplate.opsForSet().members("chat:conversations:" + friendId);

        // 合并两个集合并去重
        Set<Object> allConversations = new HashSet<>(conversations_user);
        allConversations.addAll(conversations_friend);

        // 过滤出两个用户共同的会话ID
        Set<Object> commonConversationsIds = new HashSet<>();
        for (Object conversation : allConversations) {
            if (conversations_user.contains(conversation) && conversations_friend.contains(conversation)) {
                commonConversationsIds.add(conversation);
            }
        }

//        获取消息Id列表
        List<Object> deleteChatsIds = getFriendChatIds(commonConversationsIds);

//        删除hash table中的聊天信息
        deleteFriendChat(deleteChatsIds);

//        删除sorted sets中的用户对话信息
        for (Object deleteConversation : commonConversationsIds) {
            String key = "chat:messages:" + deleteConversation;
            redisTemplate.delete(key);
        }

//        删除好友列表信息  sets中的conversations
        deleteConversationFromFriendShip(userId, friendId, commonConversationsIds);

//        删除好友信息
        deleteFriendList(userId, friendId);
    }

    //    获取用户之间对话消息Ids
    private List<Object> getFriendChatIds(Set<Object> conversations) {
//        存储要删除的消息Id列表
        List<Object> deleteChatsIds = new ArrayList<>();
        for (Object conversation : conversations) {
            String chatMessageId = "chat:messages:" + conversation;
//            获取Sorted Set中的所有成员及其分数
            Set<ZSetOperations.TypedTuple<Object>> membersWithScores = redisTemplate.opsForZSet().rangeWithScores(chatMessageId, 0, -1);
            if (membersWithScores != null && !membersWithScores.isEmpty()) {
                for (ZSetOperations.TypedTuple<Object> tuple : membersWithScores) {
//                    获取具体的value
                    Object deleteMessageId = tuple.getValue();
                    deleteChatsIds.add(deleteMessageId);
                }
            } else {
                System.out.println("No data found for chatMessageId: " + chatMessageId);
            }
        }
        return deleteChatsIds;
    }

    //    删除用户之间对话消息的数据（hash table）
    private void deleteFriendChat(List<Object> chatIds) {
        String messageId = "";
        for (Object chatId : chatIds) {
            messageId = "chat:message:" + chatId;
//            删除操作
            redisTemplate.delete(messageId);
        }
    }

    private void deleteConversationFromFriendShip(String userId, String friendId, Set<Object> commonConversationIds) {
//        在好友的conversations中删除对应的信息
        for (Object conversation : commonConversationIds) {
            redisTemplate.opsForSet().remove("chat:conversations:" + userId, conversation);
            redisTemplate.opsForSet().remove("chat:conversations:" + friendId, conversation);
        }
    }

    //    删除用户好友列表信息
    private void deleteFriendList(String userId, String friendId) {
        redisTemplate.opsForSet().remove("friends:" + userId, friendId);
        redisTemplate.opsForSet().remove("friends:" + friendId, userId);
    }


    //    查询所有聊天信息记录（用户私聊信息的查询）   from-to and to-from         用这个（不使用redis查询了）    -------------------------------------------------
    public List<ChatMessages> getAllMessages(String from, String to) {
//        构建chatId
        List<String> chatIds = generateChatId(from, to);
//        1、query查询
        Query query = new Query();
        // 在这里chatIds是一个列表，会返回chatId与列表元素匹配的所有信息（其实就是对chatIds进行一个遍历，模拟chatId==chatIds[索引]匹配）
//        query.addCriteria(Criteria.where("chatId").in(chatIds));
//        query.with(Sort.by(Sort.Direction.ASC, "timestamp"));
//        query.fields().exclude("_id");
//        return mongoTemplate.find(query, ChatMessages.class, "chatMessages");
//        2、聚合管道查询
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("chatId").in(chatIds)),        // 匹配chatId在 chatIds 列表中的文档
                Aggregation.sort(Sort.Direction.ASC, "timeStamp"),           // 按 timestamp 升序排序
                Aggregation.project().andExclude("_id")
        );
        return mongoTemplate.aggregate(aggregation, "chatMessages", ChatMessages.class).getMappedResults();
    }

    public List<String> generateChatId(String senderId, String receiverId) {
        // 创建一个列表来存储两个chatId：1、from-to  2、to-from
        List<String> chatIds = new ArrayList<>();

//        生成第一个chatId  form-to
        chatIds.add(senderId + "-" + receiverId);

//        生成第二个chatId  to-from
        chatIds.add(receiverId + "-" + senderId);
        return chatIds;
    }


    //    获取好友列表
    public List<Object> getFriendListFromRedis(String userid) {
//        构建所需的redis key
        String friendDetailsKey = "friendDetails:" + userid;
        return redisTemplate.opsForHash().values(friendDetailsKey);
    }


    /*                                  工具函数                                                   */
    //    创建好友请求消息
    public Map<String, Object> createFriendRequest(String fromUserId, String toUserId, String messageContent, String username, String friendAvatar, String reuqestId) {
        Map<String, Object> friendRequest = new HashMap<>();
        friendRequest.put("fromUserId", fromUserId);
        friendRequest.put("toUserId", toUserId);
        friendRequest.put("message", messageContent);
        friendRequest.put("timeStamp", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        friendRequest.put("username", username);
        friendRequest.put("requestId", reuqestId);
        friendRequest.put("friendAvatar", friendAvatar);
        return friendRequest;
    }

}
